package com.jinx.controller;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jixia
 * @date 2022/8/30 14:07
 * @description
 */
public class TestController {
    public void main(String[] args) {

        //传入票数
        Ticket ticket = new Ticket(20);
        //创建四个新线程并且更名
        Thread thread = new Thread(ticket, "郑州站");
        Thread thread1 = new Thread(ticket, "郑州东站");
        Thread thread2 = new Thread(ticket, "郑州南站");
        Thread thread3 = new Thread(ticket, "郑州北站");
        //启动四个线程
        thread.start();
        thread1.start();
        thread2.start();
        thread3.start();

        Lock lock = new ReentrantLock();
        lock.lock();
        try {


        }finally {
            lock.unlock();
        }
    }

    public class Ticket implements Runnable {
        //未设置票数，默认为100
        private int num = 100;

        public Ticket() {
        }
        //获取传入票数
        public Ticket(int num) {
            this.num = num;
        }


        @Override
        public void run() {
            while (true) {
                //加锁，当一个进程进入时其他进程阻塞，防止数据出错
                synchronized (this) {
                    try {
                        //延时1秒
                        TimeUnit.SECONDS.sleep(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (num > 0) {
                        System.out.printf("[%s] 售出一张票，剩余%d张票%n", Thread.currentThread().getName(), --num);
                    } else {
                        System.out.printf("%n[%s] 票已售完，停止售票。", Thread.currentThread().getName());
                        break;
                    }
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
